package com.yunpuvip.sachet.rest.controller.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.yunpuvip.sachet.modular.core.exception.RestServiceExceptionEnum;
import com.yunpuvip.sachet.rest.config.properties.RestProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * @ClassName UploadController
 * @Description TODO
 * @Author Lincoln
 * @Date 2018/7/26
 * @Version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    RestProperties restProperties;

    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/img")
    @ResponseBody
    public ResponseData upload(@RequestPart("file") MultipartFile picture) {
        String suffix = ToolUtil.getFileSuffix(picture.getOriginalFilename());
        //判断文件后缀，防止被黑0101101110101010110
        String[] imgSuffix = {"gif", "png", "jpg", "jpeg"};
        if (!ArrayUtil.contains(imgSuffix, suffix)) {
            return ResponseData.error(RestServiceExceptionEnum.FILE_SUFFIX_ERROR.getCode(), RestServiceExceptionEnum.FILE_SUFFIX_ERROR.getMessage());
        }
        String pictureName = IdUtil.simpleUUID() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
        //文件夹加上日期
        String today = DateUtil.format(new Date(), "yyyyMMdd");
        try {
            String fileSavePath = restProperties.getRestUploadPath() + today + File.separator;
            File file = new File(fileSavePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fullPath = fileSavePath + pictureName;
            log.debug("upload img fullPath: {}", fullPath);
            picture.transferTo(new File(fullPath));
        } catch (Exception e) {
            return ResponseData.error(RestServiceExceptionEnum.FILE_UPLOAD_ERROR.getCode(), RestServiceExceptionEnum.FILE_UPLOAD_ERROR.getMessage());
        }
        //返回前端一个图片的URL，带上img，做nginx的路由配置
        return ResponseData.success("/img/" + today + "/" + pictureName);
    }


}
